/* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2014. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package com.android.camera.manager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.LinearLayout;

import com.android.camera.CameraActivity;
import com.android.camera.FeatureSwitcher;
import com.android.camera.Log;
import com.android.camera.ModeChecker;
import com.android.camera.R;
import com.android.camera.ui.RGK_ControlPanelLayout;
import com.android.camera.ui.ModePickerScrollView;
import com.android.camera.ui.RGK_PageControlView;
import com.android.camera.ui.RotateImageView;
import com.android.camera.ui.RGK_ScrollControlPanelLayout;
import com.android.camera.ui.RGK_XCRoundRectImageView;
import com.android.camera.ui.RGK_ScrollControlPanelLayout.OnScreenChangeListener;
import com.mediatek.camera.ISettingCtrl;
import com.mediatek.camera.setting.SettingConstants;
import com.mediatek.camera.setting.preference.IconListPreference;


import com.mediatek.camera.setting.preference.ListPreference;

import android.widget.Toast;

public class RGKSettingManager extends ViewManager implements
		View.OnClickListener, View.OnLongClickListener {
	private static final String TAG = "ModePicker";

	private ListPreference mModePreference;

	public interface OnModeChangedListener {
		void onModeChanged(int newMode);
	}

	// can not change this sequence
	// Before MODE_VIDEO is "capture mode" for UI,switch "capture mode"
	// remaining view should not show

	public static final int OFFSET = 100;
	private static final int OFFSET_STEREO_PREVIEW = OFFSET;
	private static final int OFFSET_STEREO_SINGLE = OFFSET * 2;

	private static final int DELAY_MSG_HIDE_MS = 3000; // 3s
	private static final int MODE_DEFAULT_MARGINBOTTOM = 50;
	private static final int MODE_DEFAULT_PADDING = 27;
	private static final int MODE_MIN_COUNTS = 4;
	private LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);

	// private final RotateImageView[] mModeViews = new
	// RotateImageView[MODE_NUM_ALL];
	private ModePickerScrollView mScrollView;
	private int mCurrentMode = -1;
	private OnModeChangedListener mModeChangeListener;
	private OnScreenToast mModeToast;
	private int mDisplayWidth;
	private int mModeWidth;
	private int mModeMarginBottom = MODE_DEFAULT_MARGINBOTTOM;

	private  RGK_XCRoundRectImageView[] mModeViews = null;
	
	private  RGKSubSettingPicker[] mRGKSubSettingPickers = null;

	protected ISettingCtrl mISettingCtrl;
	private ListPreference mEffectPreference;
	CameraActivity mContext;
	
	private int mCurrentClick = -1;
	private LinearLayout mViewGroupColorEffects;

	private static final String[] RGK_SUPPORT_SETTINGS = {
			//SettingConstants.KEY_COLOR_EFFECT,
			SettingConstants.KEY_VIDEO_QUALITY,
			SettingConstants.KEY_WHITE_BALANCE,
			SettingConstants.KEY_SCENE_MODE, 
			SettingConstants.KEY_EXPOSURE,
			SettingConstants.KEY_ISO, 
			SettingConstants.KEY_SELF_TIMER,
			SettingConstants.KEY_CONTINUOUS_NUMBER,
			SettingConstants.KEY_PICTURE_RATIO, 
			SettingConstants.KEY_VOICE,
			//SettingConstants.KEY_HDR, 
			//SettingConstants.KEY_SMILE_SHOT,
			//SettingConstants.KEY_GESTURE_SHOT,
			SettingConstants.KEY_PICTURE_SIZE,
		//	SettingConstants.KEY_CAMERA_TOUCH_CAPTURE,
			SettingConstants.KEY_ANTI_BANDING,
			//SettingConstants.KEY_VIDEO_TIME_LAPSE_FRAME_INTERVAL,
			SettingConstants.KEY_SLOW_MOTION};

	private int mAddToPanelNums;
	private final int mOneScreenNums = 9;
	private RGK_PageControlView pageControl;
	private RGK_ScrollControlPanelLayout scrollControlLayout;
	RGK_ControlPanelLayout controlPanelLayout1;
	RGK_ControlPanelLayout controlPanelLayout2;

	private int mSettingTimeLapseTime;
	private boolean mflag = true;
	private boolean mControlModeFlag = false;

	public boolean getControlModeFlagClick() {
		return mControlModeFlag;
	}

	// add end

	public RGKSettingManager(CameraActivity context) {
		super(context, VIEW_LAYER_OVERLAY);
		
	    mContext = context;
	}

   public int getCurrentMode() {
       return mCurrentMode;
   }

   private void highlightCurrentMode() {
	 
	   /*
	   int index = mEffectPreference.findIndexOfValue(mEffectPreference.getValue());
	   
       //int index =mEffectPreference.findIndexOfValue(mEffectPreference.getEntry()) ;
       IconListPreference iconPref = ((IconListPreference) mEffectPreference);
       
       Log.i(TAG, "current effect value i" + index +","
       		+ "mEffectPreference.getValue():"+mEffectPreference.getValue() 
       		+" ,mEffectPreference.getEntry():"+mEffectPreference.getEntry());
       //index = 0;
       
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {

           if (mCurrentClick != -1) {
               if (i == mCurrentClick) {
                   mModeViews[i].setImageResource(iconPref.getIconIdRgkHi(i));

               } else {
            	   mModeViews[i].setImageResource(iconPref.getIconIdRgk(i));
               }
           }
           
       }*/
   }

   public void setListener(OnModeChangedListener l) {
       mModeChangeListener = l;
   }

   // modify for RGK new UI solution by anxiang.xiao  20160506
   protected View getView() {
       // clearListener();
       View view = inflate(R.layout.rgk_setting_layout);
       
       mScrollView = (ModePickerScrollView) view.findViewById(R.id.mode_picker_scroller);
       mViewGroupColorEffects = (LinearLayout) view.findViewById(R.id.mode_picker);
       
       /*
       scrollControlLayout = (RGK_ScrollControlPanelLayout) view.findViewById(R.id.ll);
       
      controlPanelLayout1 = new RGK_ControlPanelLayout(getContext());
      // controlPanelLayout.setBackgroundColor(Color.GREEN);
       
      controlPanelLayout2 = new RGK_ControlPanelLayout(getContext());*/
      // controlPanelLayout2.setBackgroundColor(Color.GRAY);
      
      DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
      mDisplayWidth = Math.min(metrics.widthPixels, metrics.heightPixels);
      
      Log.i(TAG, "mDisplayWidth:"+metrics.widthPixels +",mDisplayHeight:"+metrics.heightPixels);
       
      /*
      controlPanelLayout1.setmCellHeight(mDisplayWidth / 3);
      controlPanelLayout1.setmCellWidth(mDisplayWidth / 3);
       
       controlPanelLayout2.setmCellHeight(mDisplayWidth / 3);
       controlPanelLayout2.setmCellWidth(mDisplayWidth / 3);
       
       scrollControlLayout.setOnScreenChangeListener(new OnScreenChangeListener() {
			public void onScreenChange(int currentIndex) {
				// TODO Auto-generated method stub
				// generatePageControl(currentIndex);
			}
		});*/
       
       mModeViews = new RGK_XCRoundRectImageView[RGK_SUPPORT_SETTINGS.length];
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {  
    	   mModeViews[i] = null;
       }
      mRGKSubSettingPickers = new RGKSubSettingPicker[RGK_SUPPORT_SETTINGS.length];
      for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {  
    	  mRGKSubSettingPickers[i] = null;
      }

       mISettingCtrl =  mContext.getISettingCtrl();

       for (int i = 0; i< RGK_SUPPORT_SETTINGS.length; i++ )
       {

    	   mEffectPreference = mISettingCtrl.getListPreference(RGK_SUPPORT_SETTINGS[i]);
       
    	   if (mEffectPreference != null)
    	   {
    		   mModeViews[i] = new RGK_XCRoundRectImageView(getContext()) ;
	    	   int index = mEffectPreference.findIndexOfValue(mEffectPreference.getValue());
	    	   
	           //int index =mEffectPreference.findIndexOfValue(mEffectPreference.getEntry()) ;
	           IconListPreference iconPref = ((IconListPreference) mEffectPreference);
	           mModeViews[i].setImageResource(iconPref.getIconIdRgk(index));
	           mModeViews[i].setDrawText(mEffectPreference.getEntries()[index].toString());
	           mModeViews[i].setDrawTextTitle(mEffectPreference.getTitle());
	           
	           mViewGroupColorEffects.addView(mModeViews[i]);
	           
	           mRGKSubSettingPickers[i] = new RGKSubSettingPicker(getContext(), RGK_SUPPORT_SETTINGS[i]) ;
    	   }
       }

       /*
       mAddToPanelNums = 0;
       
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
       	   
	       	if (mModeViews[i] != null)
	       	{
	       		if (mAddToPanelNums < mOneScreenNums)
	       			controlPanelLayout1.addView(mModeViews[i]);
	       		else 
	       			controlPanelLayout2.addView(mModeViews[i]);
					
	       		mAddToPanelNums++;
	       	}
         
       }

      if (controlPanelLayout1.getChildCount() > 0)
   	   scrollControlLayout.addView(controlPanelLayout1);
       
      if (controlPanelLayout2.getChildCount() > 0)
   	   scrollControlLayout.addView(controlPanelLayout2);

       // add by anxiang.xiao end 
       
       pageControl = (RGK_PageControlView) view.findViewById(R.id.pageControl);
       pageControl.bindScrollViewGroup(scrollControlLayout);
        */
       mModeWidth = getModeWidth();
       mModeMarginBottom = getDefaultMarginBottom();
       applyListener();
       highlightCurrentMode();
       return view;
   }


   private void applyListener() {
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
           if (mModeViews[i] != null) {
               mModeViews[i].setOnClickListener(this);
               mModeViews[i].setOnLongClickListener(this);
           }
       }
   }

   private void clearListener() {
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
           if (mModeViews[i] != null) {
               mModeViews[i].setOnClickListener(null);
               mModeViews[i].setOnLongClickListener(null);
               mModeViews[i] = null;
           }
       }
   }
   

   @Override
   public void onClick(View view) {
       Log.d(TAG, "onClick(" + view + ") isEnabled()=" + isEnabled() + ", view.isEnabled()="
               + view.isEnabled() + ", getContext().isFullScreen()=" + getContext().isFullScreen()
               + ",mCurrentMode = " + mCurrentMode);
       
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
           if (view == mModeViews[i])
           {
        	   mCurrentClick = i;
        	   if (mRGKSubSettingPickers[i].isShowing())
        	   {
        		   mRGKSubSettingPickers[i].hide();
        		   
        		   mCurrentClick = -1;
        	   }
        	   else 
        		   mRGKSubSettingPickers[i].show();
			
           }
           else {
        	   if (mRGKSubSettingPickers[i] != null)
        	       mRGKSubSettingPickers[i].hide();
           }
           
           onRefresh();
       }

   }

   public void hideToast() {
       Log.i(TAG, "hideToast(), mModeToast:" + mModeToast);
       if (mModeToast != null) {
           mModeToast.hideToast();
       }
   }

   // modify new RGK new UI solution by anxiang.xiao 20160506
   // private void notifyModeChanged() {
   public void notifyModeChanged() {
       if (mModeChangeListener != null) {
           mModeChangeListener.onModeChanged(getCurrentMode());
       }
   }
   
   // add for self notify 
   public void notifyModeChanged2(int mode) {
       if (mModeChangeListener != null) {
           mModeChangeListener.onModeChanged(mode);
       }
   }
   // add & modify end 

   public void onRefresh() {
       Log.d(TAG, "onRefresh() mCurrentMode=" + mCurrentMode);
       // get counts of mode supported by back camera and compute the margin
       // bottom between mode icon.
       int supportModes = ModeChecker.modesShowInPicker(getContext(), 0);
       if (supportModes < MODE_MIN_COUNTS && supportModes > 1) {
           mModeMarginBottom = (mDisplayWidth - supportModes * mModeWidth) / (supportModes - 1);
       }
       Log.d(TAG, "mModeMarginBottom:" + mModeMarginBottom);
       mLayoutParams.setMargins(0, 0, 0, 0);

       int visibleCount = 0;
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
           if (mModeViews[i] != null ) {
        	   
        	   boolean visible = true;

               mModeViews[i].setVisibility(visible ? View.VISIBLE : View.GONE);
               mModeViews[i].setLayoutParams(mLayoutParams);
               mModeViews[i].setPadding(MODE_DEFAULT_PADDING, MODE_DEFAULT_PADDING,
            		   MODE_DEFAULT_PADDING, MODE_DEFAULT_PADDING );
               if (visible) {
                   visibleCount++;
               }
               
               mEffectPreference = mISettingCtrl.getListPreference(RGK_SUPPORT_SETTINGS[i]);

               if (mEffectPreference != null)
               {
	               int index = mEffectPreference.findIndexOfValue(mEffectPreference.getValue());
	        	   
	               //int index =mEffectPreference.findIndexOfValue(mEffectPreference.getEntry()) ;
	               IconListPreference iconPref = ((IconListPreference) mEffectPreference);
	               if (mCurrentClick == i)
	            	   mModeViews[i].setImageResource(iconPref.getIconIdRgkHi(index));
	               else
	            	   mModeViews[i].setImageResource(iconPref.getIconIdRgk(index));
	               
	               mModeViews[i].setDrawText(mEffectPreference.getEntries()[index].toString());
               }

           }
       }

       if (visibleCount <= 1) { // to enable/disable background
           mScrollView.setVisibility(View.GONE);
       } else {
           mScrollView.setVisibility(View.VISIBLE);
       }
       highlightCurrentMode();
   }

   @Override
   public boolean onLongClick(View view) {
       Log.d(TAG, "onLongClick(" + view + ")");
       if (view.getContentDescription() != null) {
           if (mModeToast == null) {
               mModeToast = OnScreenToast.makeText(getContext(), view.getContentDescription());
           } else {
               mModeToast.setText(view.getContentDescription());
           }
           mModeToast.showToast();
       }
       // don't consume long click event
       return false;
   }

   @Override
   public void setEnabled(boolean enabled) {
       super.setEnabled(enabled);
       if (mScrollView != null) {
           mScrollView.setEnabled(enabled);
       }
       for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
           if (mModeViews[i] != null) {
               mModeViews[i].setEnabled(enabled);
               mModeViews[i].setClickable(enabled);
           }
       }
   }

   @Override
   protected void onRelease() {
       super.onRelease();
       mModeToast = null;
   }

   private int getModeWidth() {
       Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(),
    		   R.drawable.ic_mode_photo_normal);
       int bitmapWidth = bitmap.getWidth();
       return bitmapWidth + MODE_DEFAULT_PADDING * 2;

   }

   private int getDefaultMarginBottom() {
       // default show three and half mode icons
       return (mDisplayWidth - MODE_MIN_COUNTS * mModeWidth) / (MODE_MIN_COUNTS - 1)
               + (mModeWidth / (2 * (MODE_MIN_COUNTS - 1)));
   }

   public void setModePreference(ListPreference pref) {
       mModePreference = pref;
   }
   
   
   public void hideAllSubSetting() {
	   for (int i = 0; i < RGK_SUPPORT_SETTINGS.length; i++) {
		   
		   if (mRGKSubSettingPickers != null)
		   {
			   if (mRGKSubSettingPickers[i] != null)
	        	   mRGKSubSettingPickers[i].hide();
		   }
       }
   }
}

